package com.infocollect.common.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AesUtil {
    //偏移量,AES 为16bytes. DES 为8bytes
    private static final String IV = "V6Valwji312ld6mw";

    //私钥,AES固定格式为128/192/256 bits.即：16/24/32bytes。DES固定格式为64bits，即8bytes。
    private static final String AES_KEY="Dnakwie9zQMKplwl";

    //填充类型，DES加密把前面的AES改成DES即可
    public static final String AES_TYPE = "AES/CBC/PKCS5Padding";

//    public static void main(String[] args){
//        String sss = encode("{'name':'1adfswefss234dsfs=sddfwfsdfse6','code':'1231231'}");
//        System.out.println(sss);
//        System.out.println(decode(sss));
//    }
    public static String encode(String password){
        try {

            // 1,获取Cipher对象
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            // 指定密钥规则
            SecretKeySpec sks = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            // 2.初始化向量的秘钥长度需要根据算法而定,des 8个字节长度  aes 16个字节长度
            //这里为了方便,统一使用传来的秘钥
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, sks, iv);
//        cipher.init(Cipher.ENCRYPT_MODE, sks);
            // 3. 加密
            byte[] bytes = cipher.doFinal(password.getBytes());
            // 对数据进行Base64编码
            String encode = Base64.encodeBase64String(bytes);
            return encode;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String decode(String encodePassword){
        try {
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            SecretKeySpec sks = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, sks, iv);
//         cipher.init(Cipher.DECRYPT_MODE, sks);
            byte[] bytes = cipher.doFinal(Base64.decodeBase64(encodePassword));
            return new String(bytes);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
